<template>
    <div class="crm-expense-container">
        <el-dialog title="变更所有权" v-model="isShowDialog" :close-on-click-modal="false">
            <el-form ref="changeCrmExpenseFormRef" :model="formData" :rules="formRules" label-width="80px">
                <el-row :gutter="35">
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="支出主题" prop="expenseName">
                            <el-input v-model="formData.expenseName" placeholder="请输入支出主题" disabled></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="支出金额" prop="expenseAmount">
                            <el-input v-model="formData.expenseAmount" placeholder="请输入支出金额" disabled></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="所属用户" prop="userId">
                            <el-select v-model="formData.userId" filterable remote 
                                @change="handleCrmUserChange"
                                @click="loadCrmUserData()"
                                :remote-method="loadCrmUserData" placeholder="请选择所属用户" clearable class="w100">
								<el-option 
									v-for="item in users"
									:key="item.id"
									:label="item.userName"
									:value="item.id">
								</el-option>
							</el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="所属部门" prop="deptId">
                            <el-cascader
                                @change="handleCrmDeptChange"
								placeholder="请选择所属部门"
								v-model="formData.deptId"
								:options="depts"
								:props="{expandTrigger: 'hover', emitPath: false, checkStrictly: true, value: 'id', label: 'deptName', children: 'children' }"
								class="w100"
                                filterable
								clearable>
							</el-cascader>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <div class="color-warning">
                            <p>数据权限：变更数据权限的归属所有者，拥有归属权限的用户或部门将可见或可操作。</p>
                        </div>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="onCancel">取 消</el-button>
                    <el-button type="primary" @click="onSubmit">保 存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts">
import { reactive, toRefs, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getCrmExpense, changeCrmExpense } from '/@/api/crm/expense/index';
import { getCrmUserList } from '/@/api/crm/user/index';
import { getCrmDeptList } from '/@/api/crm/dept/index';
import { lineToTreeData } from '/@/utils/commonFunction';
export default {
    name: 'crm/expense/change',
    components: { },
    setup(props, context) {
        const changeCrmExpenseFormRef = ref();
        const state = reactive({
            isShowDialog: false,
            users: [],
            depts: [],
            dorgs: [],
            formData: {},
            formRules : {}
        });

        // 加载客户数据
        const loadCrmUserData = (query?: string) => {
            if(query == '') return;
            getCrmUserList({userName: query}).then((res) => {
                if(res.code == 0){
                    state.users = res.data;
                }
            });
        }

        const handleCrmUserChange = (id: string) => {
            const user = state.users.find(item => item.id == id);
            state.formData.userId = user?.id;
            state.formData.userName = user?.userName;
        }
        
        const loadCrmDeptData = () => {
            getCrmDeptList().then((res) => {
                if(res.code == 0 && res.data?.length > 0){
                    state.dorgs = res.data;
                    state.depts = lineToTreeData(res.data);
                }
            });
        }

        const handleCrmDeptChange = (id: string) => {
            const dept = state.dorgs.find(item => item.id == id);
            state.formData.deptId = dept?.id;
            state.formData.deptName = dept?.deptName;
        }

        // 打开弹窗
        const openDialog = (row?: object) => {
            state.isShowDialog = true;
            if(row){
                getCrmExpense({id: row.id}).then((res) => {
                    if(res.code == 0){
                        state.formData = Object.assign({}, res.data);
                        state.users = [{id: state.formData.userId, userName: state.formData.userName}];
                        //state.depts = [{id: state.formData.deptId, deptName: state.formData.deptName}];
                    }
                });
            }
            loadCrmDeptData();
        };
        // 关闭弹窗
        const closeDialog = (row?: object) => {
            state.isShowDialog = false;
            for(var key in state.formData) {
                state.formData[key] = undefined;
            }
            changeCrmExpenseFormRef.value.resetFields();
        };
        // 取消
        const onCancel = () => {
            closeDialog();
        };
        // 新增
        const onSubmit = () => {
            changeCrmExpenseFormRef.value.validate(valid => {
                if(valid){
                    let params = {
                        id: state.formData.id,
                        userId: state.formData.userId,
                        deptId: state.formData.deptId,
                        userName: state.formData.userName,
                        deptName: state.formData.deptName,
                    }
                    changeCrmExpense(params).then((res) => {
                        if(res.code == 0){
                            ElMessage.success('修改成功');
                            closeDialog();
                            context.emit('submit');
                        }
                    });
                }
            });
        };
        return {
            changeCrmExpenseFormRef,
            openDialog,
            closeDialog,
            onCancel,
            onSubmit,
            loadCrmUserData,
            loadCrmDeptData,
            handleCrmUserChange,
            handleCrmDeptChange,
            ...toRefs(state),
        };
    },
};
</script>